package org.mch.test;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * 描述：Apache HTTP封闭使用；<BR>
 *
 * @author MCH；Date：2008-10-01<BR>
 *
 */
public class MHttpCall2 {
	private String USERAGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0";
	public static final Map<String, String> headerMap = new HashMap<String, String>();
	static {
		headerMap.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		headerMap.put("Accept-Encoding", "gzip, deflate");
		headerMap.put("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
		headerMap.put("Connection", "keep-alive");
		headerMap.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0");
	}

	public MHttpCall2() {
		super();
	}

	public void callUTF8(ItfParamRequest requestParam, Map<String, String> paraMap) {
		call(requestParam, paraMap, Consts.UTF_8);
	}

	public void call(ItfParamRequest requestParam, Map<String, String> paraMap, Charset charset) {
		HttpClientBuilder clientBuilder = null;
		CloseableHttpClient clientRequest = null;
		try {
			clientBuilder = HttpClientBuilder.create();
			clientBuilder.setUserAgent(USERAGENT);

			clientRequest = clientBuilder.build();

			HttpResponse response = null;

			if ("POST".equalsIgnoreCase(requestParam.getRequestType())) {
				// 1、设置Post请求，相关相关参数，地址，传值等
				HttpPost post = getHttpPost(requestParam, paraMap, charset, headerMap);

				// 2、执行请求，并返回响应对象
				response = clientRequest.execute(post);
			} else {
				//
			}

			// buildCookieStore(response);

			// 5、通过响应对象获取响应消息实体
			HttpEntity entity = response.getEntity();
			System.out.println("Login form get: " + response.getStatusLine());

			System.out.println(entity.toString());
			System.out.println(IOUtils.toString(entity.getContent()));

			// 99、消灭响应消息实体
			EntityUtils.consume(entity);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				clientRequest.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	protected void buildCookieStore(HttpResponse response) {
		System.out.println("----setCookieStore");
		BasicCookieStore cookieStore = new BasicCookieStore();
		// JSESSIONID
		String setCookie = response.getFirstHeader("Set-Cookie").getValue();
		Header[] headers = response.getAllHeaders();
		for (int i = 0, len = headers.length; i < len; i++) {
			String name = headers[i].getName();
			String value = headers[i].getValue();
			if ("Set-Cookie".equalsIgnoreCase(name)) {
				System.out.println(Arrays.toString(value.split(";")));
			}
		}
		String JSESSIONID = setCookie.substring("JSESSIONID=".length(), setCookie.indexOf(";"));
		System.out.println("JSESSIONID:" + JSESSIONID);
		// 新建一个Cookie
		BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", JSESSIONID);
		cookie.setVersion(0);
		cookie.setDomain("www.mchweb.net");
		cookie.setPath("/member");
		// cookie.setAttribute(ClientCookie.VERSION_ATTR, "0");
		// cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "127.0.0.1");
		// cookie.setAttribute(ClientCookie.PORT_ATTR, "8080");
		// cookie.setAttribute(ClientCookie.PATH_ATTR, "/CwlProWeb");
		cookieStore.addCookie(cookie);
	}

	protected HttpPost getHttpPost(ItfParamRequest requestParam, Map<String, String> paraMap, Charset charset) {
		return getHttpPost(requestParam, paraMap, charset, null);
	}

	protected HttpPost getHttpPost(ItfParamRequest requestParam, Map<String, String> paraMap, Charset charset,
			Map<String, String> headerMap) {
		// 1、设置Post请求，及请求地址
		HttpPost post = new HttpPost(requestParam.getUrl());

		setHttpPostHeader(post, headerMap);

		// 2、设置参数键值
		List<NameValuePair> paraList = buildNameValuePair(paraMap);

		// 3、设置提交编码
		post.setEntity(new UrlEncodedFormEntity(paraList, charset));

		return post;
	}

	private void setHttpPostHeader(HttpPost post, Map<String, String> headerMap) {
		if (headerMap == null || headerMap.isEmpty()) {
			return;
		}

		String[] keys = headerMap.keySet().toArray(new String[0]);
		for (int i = 0, len = keys.length; i < len; i++) {
			String kkey = keys[i];
			post.addHeader(kkey, headerMap.get(kkey));
		}
	}

	protected HttpGet getHttpGet(ItfParamRequest requestParam, Map<String, String> paraMap, Charset charset) {
		// 1、设置Post请求，及请求地址
		HttpGet get = new HttpGet(requestParam.getUrl());

		// 2、设置参数键值
		List<NameValuePair> paraList = buildNameValuePair(paraMap);
		// 3、设置提交编码
		// get.setParams(params);etEntity(new UrlEncodedFormEntity(paraList,
		// charset));

		return get;
	}

	public List<NameValuePair> buildNameValuePair(Map<String, String> paraMap) {
		if (paraMap == null || paraMap.isEmpty()) {
			return null;
		}

		List<NameValuePair> list = new ArrayList<NameValuePair>();
		String[] keys = paraMap.keySet().toArray(new String[0]);
		for (int i = 0, len = keys.length; i < len; i++) {
			String kkey = keys[i];
			list.add(new BasicNameValuePair(kkey, paraMap.get(kkey)));
		}

		return list;
	}

	public static void main(String[] args) {

		MHttpCall2 call = new MHttpCall2();
		Map<String, String> paraMap = new HashMap<String, String>();
		paraMap.put("code", "N7777");
		paraMap.put("name", "TEST");

		call.callUTF8(new TestRequestParam(), paraMap);
	}
}
